package dispatcher;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;


public class DataDispatcher {
	
	/**
	 * Map
	 *  |- filename writer
	 *  |- filename writer
	 */
	Map<String, BufferedWriter> writers;
	
	public DataDispatcher(File dispatchDir) throws Exception {
		if (!dispatchDir.exists() || !dispatchDir.isDirectory()) {
			throw new Exception(dispatchDir + " is not a directory");
		}
		
		File[] files = dispatchDir.listFiles();
		this.writers = new HashMap<String, BufferedWriter>();
		
		for (int i = 0; i < files.length; i++) {
			this.writers.put(files[i].getName().replace(".txt", ""), new BufferedWriter(new FileWriter(files[i])));
		}
	}
	
	public Set<String> getNames() {
		return this.writers.keySet();
	}
	
	public void writeTo(String name, String value) throws Exception {
		this.writers.get(name).write("\n" + value);
	}
	
	public void finalize() throws Exception {
		Iterator<Entry<String, BufferedWriter>> it = this.writers.entrySet().iterator();
		
		while (it.hasNext()) {
			it.next().getValue().close();
		}
	}
}
